import {Plugin} from '@ckeditor/ckeditor5-core';
import {Widget} from '@ckeditor/ckeditor5-widget';
import MediaEmbedEditing from "@ckeditor/ckeditor5-media-embed/src/mediaembedediting";
import MediaEmbedUI from "@ckeditor/ckeditor5-media-embed/src/mediaembedui";
import AutoMediaEmbed from "@ckeditor/ckeditor5-media-embed/src/automediaembed";
import {createDropdown, SplitButtonView} from '@ckeditor/ckeditor5-ui';
import MediaFormView from "@ckeditor/ckeditor5-media-embed/src/ui/mediaformview";
import mediaIcon from '@ckeditor/ckeditor5-media-embed/theme/icons/media.svg';
import {FileDialogButtonView} from "@ckeditor/ckeditor5-upload";

class MyMediaEmbedUI extends MediaEmbedUI {
    init() {
        const editor = this.editor;
        const command = editor.commands.get('mediaEmbed');
        const registry = editor.plugins.get(MediaEmbedEditing).registry;
        this._createUploadVideoUi();
        editor.ui.componentFactory.add('mediaEmbed', locale => {
            const dropdown = createDropdown(locale, SplitButtonView);
            const mediaForm = new MediaFormView(getFormValidators(editor.t, registry), editor.locale);

            this._setUpDropdown(dropdown, mediaForm, command, editor);
            this._setUpForm(dropdown, mediaForm, command);

            return dropdown
        });
    }

    _setUpDropdown(dropdown, form, command) {
        const editor = this.editor;

        dropdown.bind('isEnabled').to(command);
        dropdown.panelView.children.add(form);

        dropdown.buttonView.actionView = editor.ui.componentFactory.create('uploadVideo');

        dropdown.buttonView.on('open', () => {
            form.disableCssTransitions();
            form.url = command.value || '';
            form.urlInputView.fieldView.select();
            form.focus();
            form.enableCssTransitions();
        }, {priority: 'low'});

        dropdown.on('submit', () => {
            if (form.isValid()) {
                editor.execute('mediaEmbed', form.url);
                closePanel();
            }
        });

        dropdown.on('change:isOpen', () => form.resetFormStatus());
        dropdown.on('cancel', () => closePanel());

        function closePanel() {
            editor.editing.view.focus();
            dropdown.isOpen = false;
        }
    }

    _createUploadVideoUi() {
        const editor = this.editor;
        editor.ui.componentFactory.add('uploadVideo', locale => {
            const view = new FileDialogButtonView(locale);
            view.set({acceptedType: 'video/mp4', allowMultipleFiles: false});
            view.buttonView.set({icon: mediaIcon, label: editor.t('Insert media'), tooltip: true});
            view.on('done', (evt, files) => {
                if (window.AdminUploadAdapter) {
                    (new window.AdminUploadAdapter()).upload(files, function (url) {
                        editor.execute('mediaEmbed', url)
                    });
                } else {
                    editor.execute('mediaEmbed', URL.createObjectURL(files[0]))
                }
            });
            return view;
        });
    }
}

// 与 UploadVideo 冲突，同时保能使用一个
export default class MediaEmbed extends Plugin {
    /**
     * @inheritDoc
     */
    static get requires() {
        return [MediaEmbedEditing, MyMediaEmbedUI, AutoMediaEmbed, Widget];
    }

    /**
     * @inheritDoc
     */
    static get pluginName() {
        return 'MediaEmbed';
    }
}

function getFormValidators(t, registry) {
    return [
        form => {
            if (!form.url.length) {
                return t('The URL must not be empty.');
            }
        },
        form => {
            if (!registry.hasMedia(form.url)) {
                return t('This media URL is not supported.');
            }
        }
    ];
}